package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.mapper.UserMapper;
import com.tanhua.pojo.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    /**
     * @param phone            手机号
     * @param verificationCode 验证码
     * @return
     */
    public Map<String, String> loginVerification(String phone, String verificationCode) {

        String key = "CHECK_CODE_" + phone;
        Map<String, String> map = new HashMap<>();
        map.put("isNew", "false");

        //判断验证码是否正确, 是否错误(验证码过期也是错误)
        String code = redisTemplate.opsForValue().get(key);
        if (!StringUtils.equals(verificationCode, code)) {
            //验证码错误
            return null;
        }

        //验证码校验完成之后需要废弃删除
        redisTemplate.delete(key);

        //如果验证码正确,则拿着手机号去判断是否为新用户,如果是新用户则直接注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMobile, phone);
        User user = userMapper.selectOne(queryWrapper);
        if (null == user) {
            //注册用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            userMapper.insert(user);
            map.put("isNew", "true");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());

        // 登录或者注册成功, 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12h后过期
                .compact();

        map.put("token", token);

        //将用户登录成功的消息发送至消息队列
        //tanhua-sso-login是topic
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id", user.getId());
        map1.put("dateTime", DateTime.now().toDateTime());
        rocketMQTemplate.convertAndSend("tanhua-sso-login", map1);

        return map;
    }

    //
    public User queryUserByToken(String token) {

        // 通过token解析数据
        User user = new User();
        try {
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            //System.out.println(body); //{id=2, exp=1605513392}
            String id = body.get("id").toString();
            user.setId(Long.valueOf(id));
            //TODO token解析出来之后只有用户的id信息, 没有mobile信息, 如果想获取的话还要
            //TODO 每次查询数据库, 所以第一次从数据库查询出来之后这里对该token中包含的用户id对应的用户的手机号进行缓存.
            String key = "TANHUA_USER_MOBILE_" + id;
            if (redisTemplate.hasKey(key)) {
                user.setMobile(redisTemplate.opsForValue().get(key));
            } else {
                User user1 = userMapper.selectById(id);
                if (null != user1) {
                    user.setMobile(user1.getMobile());

                    //设置用户手机信息的过期时间和token过期时间一样
                    Long time = Long.valueOf(body.get("exp").toString())*1000 - System.currentTimeMillis();
                    redisTemplate.opsForValue().set(key, user1.getMobile(),time, TimeUnit.MILLISECONDS);
                }
            }
            return user;
        } catch (ExpiredJwtException e) {
            System.out.println("token已经过期！");
        } catch (Exception e) {
            System.out.println("token不合法！");
        }

        //返回根据token和秘钥解析出的用户
        return null;
    }
}
